package cn.toolck.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.MessageListenerContainer;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {
    @Bean
    public Queue queue() {
        return QueueBuilder
                .nonDurable("queue.toolck.pay")
                .ttl(10 * 1000)
                .deadLetterExchange("ex.toolck.pay.dlx")
                .deadLetterRoutingKey("toolck.pay.dlx")
                .build();
    }

    @Bean
    public Exchange exchange() {
        return ExchangeBuilder.directExchange("ex.toolck.pay").build();
    }

    @Bean
    Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with("toolck.pay").noargs();
    }

    @Bean
    public Queue queueDlx() {
        return QueueBuilder.nonDurable("queue.toolck.pay.dlx").build();
    }

    @Bean
    public Exchange exchangeDlx() {
        return ExchangeBuilder.directExchange("ex.toolck.pay.dlx").build();
    }

    @Bean
    Binding bindingDlx() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with("toolck.pay.dlx").noargs();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }

    @Bean
    public RabbitListenerContainerFactory<?> messageListenerContainer(ConnectionFactory connectionFactory) {
        final SimpleRabbitListenerContainerFactory listenerContainerFactory = new SimpleRabbitListenerContainerFactory();
        listenerContainerFactory.setConnectionFactory(connectionFactory);
//        listenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return listenerContainerFactory;
    }
}
